/*
 * @Author: csy 
 * @Date: 2019-05-09 16:09:33 
 * @Last Modified by: csy
 * @Last Modified time: 2019-06-20 15:24:37
 */
layui.use(['table', 'zlPinYin', 'zlContext'], function (exports) {
    var $ = layui.$
        , zlContext = layui.zlContext
        , layer = layui.layer
        , table = layui.table
        , form = layui.form
        , zlPinYin = layui.zlPinYin
        , zlConfig = layui.zlConfig
        , statusName = zlConfig.global.result.statusName
        , msgName = zlConfig.global.result.msgName
        , dataName = zlConfig.global.result.dataName
        , OK = zlConfig.global.result.okState
        , fullheight = 'full-30'
        , customCurr = 1
        , isloadsearch = false
        , frmlayerIndex;
    fullheight = zlContext.setMaxHeihgt(0);

    // 渲染表格
    var loadingLayer = layer.msg('数据加载中，请稍候...', { icon: 16, time: false, shade: 0.1 });
    var tbHomepage = table.render({
        elem: '#tbHomepage'
        , sortload: true
        , height: fullheight
        , response: zlConfig.global.gridResponse
        , url: layui.cache['contentPath'] + '/manager/corehomepage/query'
        , method: 'post'
        , updId: '012A3E1E0483483791BBD7A7DBB3E7CE'
        , toolbar: "#toolbar-homepage"
        , defaultToolbar: ['filter']
        , limit: 20
        , limits: [20, 50, 100, 200, 500, 1000]
        , page: true
        , cols: [[ //表头
            { type: 'numbers', fixed: 'left', title: '#' }
            , { type: 'checkbox', fixed: 'left' }
            , { field: 'OBJCODE', title: '编号', sort: true, width: 260 }
            , { field: 'OBJNAME', title: '名称', sort: true, width: 240 }
            , { field: 'SYS_MODIFYTIME', title: '最后修改时间', sort: true, width: 180 }
            , { field: 'HP_MIAOS', title: '描述'}
            , { fixed: 'right', width: 280, title: '操作', align: 'center', toolbar: '#operation-btn-homepage' }
        ]]
        , done: function (res, curr, count) {
            layer.close(loadingLayer);
        }
        , event:
        {
            onRowdbClick: function (field, row) {
                gridAction.viewRow(row);
            }
        }
    });

    var gridAction = {
        currentEditObj: undefined,
        gridEdit: function (row, type, readonly) {
            // 弹出框内容
            var readonly = readonly && readonly != 0 ? 'disabled' : '';
            var frm = [
                '<div class="site-block"> <form id ="frmGridField" class="layui-form"  action="">'
                , '	<div class="layui-form-item layui-hide">'
                , '		<div class="layui-input-block">'
                , '			<input type="text" name="EDITTYPE" class="layui-input">'
                , '			<input type="text" name="RWID" class="layui-input">'
                , '		</div>'
                , '	</div>'
                , '	<div class="layui-form-item">'
                , '		<label class="layui-form-label">名称:</label>'
                , '		<div class="layui-form layui-input-block" lay-filter="VER_SUOSXT">'
                , '			<input type="text" name="OBJNAME" required ' + readonly + ' lay-verify="required" class="layui-input" maxlength="80">'
                , '		</div>'
                , '	</div>'
                , '	<div class="layui-form-item">'
                , '		<label class="layui-form-label">编号:</label>'
                , '		<div class="layui-input-block">'
                , '			<input type="text" name="OBJCODE" required ' + readonly + ' lay-verify="required|verifyObjcode" class="layui-input" maxlength="50">'
                , '		</div>'
                , '	</div>'
                , '	<div class="layui-form-item">'
                , '		<label class="layui-form-label">描述:</label>'
                , '		<div class="layui-input-block">'
                , '			<textarea  name="HP_MIAOS" class="layui-textarea" maxlength="1300" ' + readonly + '></textarea>'
                , '		</div>'
                , '	</div>'
                , '	<div class="layui-form-item">'
                , '		<label class="layui-form-label">排序:</label>'
                , '		<div class="layui-input-block">'
                , '			<input type="text" name="SYS_SORT" ' + readonly + ' lay-verify="numberInt" class="layui-input" maxlength="5">'
                , '		</div>'
                , '	</div>'
                , '	<div class="layui-form-item' + (readonly == 'disabled' ? ' layui-hide"' : '"') + '>'
                , '		<div class="layui-input-block">'
                , '		  <button class="layui-btn" lay-submit lay-filter="frmGridField" ' + readonly + '>保存</button>'
                , '		</div>'
                , '	</div>'
                , '</form></div>'
            ];

            frmlayerIndex = layer.open({
                type: 1,
                id: 'addHomepageLayer',
                area: ['100%', '100%'],
                content: frm.join(''),
                title: readonly == 'disabled' ? '查看首页设计' : ('edit' == type ? '编辑首页设计' : ('clone' == type ? '克隆首页设计' : '新增首页设计')),
                success: function (layero, index) {
                    if ('edit' == type || 'clone' == type) {
                        zlContext.autoFill($('#frmGridField'), row);
                        $('#frmGridField input[name=EDITTYPE]').val(type);
                    } else {
                        /**设置隐藏属性*/
                        $('#frmGridField input[name=EDITTYPE]').val('new');
                        form.render();
                        $('#frmGridField input[name=OBJNAME]').change(function () {
                            var v = $('#frmGridField input[name=OBJNAME]').val();
                            /**设置版本更新信息名 */
                            var v1 = zlPinYin.C(v);
                            $('#frmGridField input[name=OBJCODE]').val(v1);
                            form.render();
                        });
                    }
                },
                cancel: function (index, layero) {
                    if (type == 'edit' && readonly != 'disabled') {
                        zlContext.isFormDataChange('frmGridField', gridAction.currentEditObj.data, gridAction, index);
                        return false;
                    }
                }
            });
        },
        //查看
        viewRow: function (row) {
            gridAction.gridEdit(row, "edit", true);
        },
        //编辑
        editRow: function (row) {
            gridAction.gridEdit(row, "edit", false);
        },
        //新增
        newRow: function () {
            gridAction.gridEdit(null, "new", false);
        },
        //删除
        delRows: function (rows) {
            if (!rows || rows.length <= 0) {
                zlContext.warnMsg("请选择需要删除的首页设计");
                return;
            }
            zlContext.confirm('询问', '是否要删除所选的首页设计?', function (index) {
                // var param = { id: rows[0]['RWID'] };
                var ids = [];
                for (var i = 0; i < rows.length; i++) {
                    ids.push(rows[i]['RWID'])
                }
                //提交删除
                zlContext.deletePost(layui.cache['contentPath'] + '/manager/corehomepage/remove', { "ids": ids.join(",") }, function (result) {
                    if (result[statusName] == OK) {
                        gridAction.refreshGrid('del', null);
                        zlContext.successMsg('删除成功');
                    }
                    else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
                layer.close(index);
            });
        },
        //保存
        submit: function (fields) {
            var editType = $('#frmGridField input[name=EDITTYPE]').val();
            if ('new' == editType) {
                zlContext.put(layui.cache['contentPath'] + '/manager/corehomepage/add', fields, function (result) {
                    if (result[statusName] == OK) {
                        gridAction.refreshGrid(editType, result[dataName]);
                        layer.close(frmlayerIndex);
                        zlContext.successMsg('保存成功');
                        return true;
                    } else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
            } else if ('edit' == editType) {
                zlContext.post(layui.cache['contentPath'] + '/manager/corehomepage/modify', fields, function (result) {
                    if (result[statusName] == OK) {
                        gridAction.refreshGrid(editType, result[dataName]);
                        layer.close(frmlayerIndex);
                        zlContext.successMsg('保存成功');
                        return true;
                    } else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
            } else if ('clone' == editType) {
                if (!fields['RWID']) {
                    zlContext.warnMsg("克隆失败：无法获取被克隆对象的RWID");
                    return false;
                }
                zlContext.post(layui.cache['contentPath'] + '/manager/corehomepage/clone', fields, function (result) {
                    if (result[statusName] == OK) {
                        gridAction.refreshGrid('clone', result[dataName]);
                        layer.close(frmlayerIndex);
                        zlContext.successMsg('克隆成功');
                        return true;
                    } else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
            }
            return false;
        },
        //搜索
        search: function () {
            var param = {}
            if ($('#editSeacherValue').val().length > 0) {
                param['SEARCHVALUE'] = $('#editSeacherValue').val();
                isloadsearch = true;
            }
            layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
        },
        //刷新
        refresh: function () {
            $('#edtSeacherValue').val("")
            var param = {}
            if ($('#editSeacherValue').val().length > 0) {
                param['SEARCHVALUE'] = $('#editSeacherValue').val();
            }
            layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
        },
        //刷新行
        refreshGrid: function (type, row) {
            /**刷新行 */
            if (type == 'edit' && gridAction.currentEditObj) {
                gridAction.currentEditObj.update(row);
            }
            else {
                var addLoading = layer.load();
                tbHomepage.reload({
                    where: {
                        'SEARCHVALUE': $('#editSeacherValue').val()
                    },
                    page: {
                        curr: customCurr
                    },
                    done: function (res, curr, count) {
                        $('#editSeacherValue').val($('.zl-container').attr('data-search'));
                        layer.close(addLoading);
                        customCurr = curr;
                    }
                });
            }
        },
        //设计
        design: function (row) {
            var frmobj = layer.open({
				type: 2,
				limit: 999,
				maxmin: true,
				title: row['OBJNAME'] + '-首页设计',  
				id: 'homepageDesignLayer',
				area: ['100%', '100%'],
                method:"post",
                content: layui.cache['contentPath'] + '/manager/corehomepage/design?tokenId=' + getTokenId(),
                params:{'RWID':row['RWID']},
                success:function(){

                },
				cancel: function (index, layero) {
					layer.close(index);
					return false;
				}
			});
        },
        //预览
        preview: function (row) {
            layer.open({
                type: 2,
                maxmin: true,
                title: '首页预览',
                id: 'formPreview',
                area: ['100%', '100%'],
                method: "post",
                content: layui.cache['contentPath'] + '/manager/corehomepage/preview?tokenId=' + getTokenId(),
                params: { "RWID": row['RWID']},
            });
        },
        //克隆
        clone: function (row) {
            gridAction.gridEdit(row, 'clone', false);
        }
    }

    $('.zl-container').on('keyup', '#editSeacherValue', function (event) {
        var keyCode = event.keyCode;
        $('.zl-container').attr('data-search', $(this).val())
        if (keyCode == 13) {
            customCurr = 1;
            gridAction.search();
        } else if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
            customCurr = 1;
            $('#btnSeacher').trigger('click');
            isloadsearch = false;
        }
    });

    //监听刷新的事件
    layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (param) {
        var index = layer.msg('数据查询中，请稍候...', { icon: 16, time: false, shade: 0.1 });
        var loadGridData = function (tableId, url, param) {
            //  当param为空时，会将上次的缓存参数再次传入后台 需使用方法级渲染
            tbHomepage.reload({
                url: url
                , height: fullheight
                , method: 'post'
                , page: {
                    curr: customCurr
                }
                , where: param
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
                , done: function (res, curr, count) {
                    $('#editSeacherValue').val($('.zl-container').attr('data-search'));
                    layer.close(index);
                    customCurr = curr;
                }
            });
        }
        //刷新
        loadGridData('tbHomepage', layui.cache['contentPath'] + '/manager/corehomepage/query', param);
    });

    //头工具栏事件
    table.on('toolbar(tbHomepage)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'addHomepage':
                gridAction.newRow();
                break;
            case 'delHomepage':
                var rows = checkStatus.data;
                gridAction.delRows(rows);
                break;
            case 'refreshHomepage':
                gridAction.refresh();
                break;
            case 'btnSeacher':
                customCurr = 1;
                gridAction.search();
                break;
        }
    });
    //监听行工具事件
    table.on('tool(tbHomepage)', function (obj) {
        var row = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        if (layEvent === 'detail') { //查看
            gridAction.viewRow(row)
        } else if (layEvent === 'edit') { //编辑
            gridAction.currentEditObj = obj;
            gridAction.editRow(row);
        } else if (layEvent === 'design') { //设计
            gridAction.currentEditObj = obj;
            gridAction.design(row);
        } else if (layEvent === 'preview') { //预览
            gridAction.currentEditObj = obj;
            gridAction.preview(row);
        } else if (layEvent === 'clone') { //克隆
            gridAction.currentEditObj = undefined;
            //克隆row字段内容
            var cloneRow = JSON.parse(JSON.stringify(row));
            gridAction.clone(cloneRow);
        } else if (layEvent === 'del') { //删除
            gridAction.currentEditObj = obj;
            gridAction.delRows([row]);
        }
    });

    //校验
    form.verify({
        verifyObjcode: function (value, item) {
            if (value) {
                if (!new RegExp("^[a-zA-Z0-9_]{0,50}$").test(value)) {
                    return '编号只能包含[字母、数字、下划线，且最大长度不超过50个字符]';
                }
            }
        }
    });

    //提交
    form.on('submit(frmGridField)', function (frm) {
        if ($(frm.elem).hasClass('getField')) {
            gridAction.newFields = frm.field
            return false;
        }
        return gridAction.submit(frm.field);
    });
    //当浏览器窗口大小改变时，设置显示内容的高度  
    window.onresize = function () {
        fullheight = zlContext.setMaxHeihgt(0);
    }
});